#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdlib.h>
#include <getopt.h>

#define FIFO_FILE_1W ".fifo_file_1w"
#define FIFO_FILE_2W ".fifo_file_2w"

#define STR_1 " HELLO WORLD "
#define STR_2 " HAHAHAHA "

int			sig_stop = 0;

void sig_pipe(int signum)
{
	if( SIGPIPE == signum)
	{
		sig_stop = 1;
	}
}

int main(int argc, char **argv)
{
	int					mode = -1;
	int					rv = -1;
	int					fdr_fifo = -1;
	int					fdw_fifo = -1;
	char				buf[1024];

	static struct option long_option[] = {
		{"mode", required_argument, NULL, 'm'},
		{0,0,0,0}
	};

	while((rv = getopt_long(argc,argv, "m:", long_option, NULL)) != -1)
	{
		switch(rv)
		{
			case 'm' : mode = atoi(optarg);

		}
	}

	if(mode == -1)
	{
		printf(" mode error \n");
		return -1;
	}

	signal(SIGPIPE, sig_pipe);

	if(access(FIFO_FILE_1W, F_OK))
	{
		printf("fifo file : %s , create it now \n",FIFO_FILE_1W);
		mkfifo(FIFO_FILE_1W, 0666);
	}
	if(access(FIFO_FILE_2W, F_OK))
	{
		printf("fifo file : %s , create it now \n",FIFO_FILE_2W);
		mkfifo(FIFO_FILE_2W, 0666);	
	}

	if( 0 == mode)
	{
		printf(" run 0 \n");

		fdw_fifo = open(FIFO_FILE_1W, O_WRONLY);
		if( fdw_fifo < 0)
		{
			printf(" 0 : fdw_fifo error \n");
			return -2;
		}	
		
		fdr_fifo = open(FIFO_FILE_2W, O_RDONLY);
		if(fdr_fifo < 0)
		{
			printf("0 : fdr_fifo error \n");
			return -3;
		}

		write(fdw_fifo, STR_1, strlen(STR_1));

		memset(buf,0,sizeof(buf));
		read(fdr_fifo, buf, sizeof(buf));

		printf(" 0 : %s \n", buf);

		return 0;
	}
	else if( 1 == mode)
	{
		printf(" run 1 \n");

		fdr_fifo = open(FIFO_FILE_1W, O_RDONLY);
		if( fdr_fifo < 0)
		{
			printf(" 1 : fdr_fifo error \n");
			return -4;
		}	

		fdw_fifo = open(FIFO_FILE_2W, O_WRONLY);
		if( fdw_fifo < 0)
		{
			printf(" 1 : fdw_fifo error \n");
			return -5;
		}
		
		memset(buf, 0, sizeof(buf));
		read(fdr_fifo, buf, sizeof(buf));

		printf(" 1 : %s \n",buf);
		strncat(buf, STR_2, strlen(STR_2));

		write(fdw_fifo, buf, strlen(buf));

		return 0;

	}
	
}






